import {Module} from  'vuex'
import {ILoginState} from './types'
import {IRootState} from '../types'
import localCache from '@/utils/cache'
import {accountLoginRequest,requestUserInfoById,requestUserMenusByRoleId} from '@/service/login/login'
import { IAccount} from '@/service/login/types'
import router from '@/router'
import {mapMenusToRoutes,mapMenusToPermissions} from '@/utils/map-menus'

//接收两个参数  一个是当前数据的类型，一个是根的类型
export const loginModule:Module<ILoginState,IRootState> = {
  namespaced:true,
  state(){
    return{
      token:'',
      userInfo:{},
      userMenus:{},
      permission:[]
    }
  },
  getters:{

  },
  actions:{
    async accountLoginAction({commit,dispatch},payLoad:IAccount){
      //1.实现登录逻辑
      const loginResult = await accountLoginRequest(payLoad)
      const {id,token} = loginResult.data
      commit('changeToken',token)
      localCache.setCache('token',token)

      //发送初始化的请求（完整的role/department）
      dispatch('getInitialDataAction',null,{root:true})


      //2.请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('changeUserInfo',userInfo)
      localCache.setCache('userInfo',userInfo)

      //3.请求用户菜单
      const userMenusResult = await requestUserMenusByRoleId(userInfo.role.id)
      const userMenus = userMenusResult.data
      commit('changeUserMenus',userMenus)
      localCache.setCache('userMenus',userMenus)


      //4.跳转首页
      router.push('/main')
    },
    //从本地读取数据，将数据存储到vuex中
    loadLocalLogin({commit,dispatch}){
      const token = localCache.getCache('token')
      if(token){
        commit('changeToken',token)
        dispatch('getInitialDataAction',null,{root:true})
      }
      const userInfo = localCache.getCache('userInfo')
      if(userInfo){
        commit('changeUserInfo',userInfo)
      }
      const userMenus = localCache.getCache('userMenus')
      if(userMenus){
        commit('changeUserMenus',userMenus)
      }
    }

    // phoneLoginAction({commit},payLoad:any){
    //   console.log('执行phoneLoginAction',payLoad);
    // }
  },
  mutations:{
    changeToken(state,token:string){
      state.token = token
    },
    changeUserInfo(state,userInfo:object){
      state.userInfo = userInfo
    },
    changeUserMenus(state,userMenus){
      state.userMenus = userMenus

      //将userMenus映射到路由中
      const routes = mapMenusToRoutes(userMenus)

      //然后再将routes =>router.main.children
      //利用动态路由  router.addRoute
      routes.forEach((route)=>{
        router.addRoute('main',route)
      })
      //获取用户按钮权限
    const permission = mapMenusToPermissions(userMenus)
    state.permission = permission


    }
  }
}
